const express = require("express");
const router = express.Router();
const LoginServices = require("../services/loginServices");
const { verifyJson, FormatJson } = require("../utils/tool");
const { ValidationError } = require("../utils/errors");
// 登录
router.post("/login", async (req, res, next) => {
    if (!req.body.isOldPassword) {
        console.log("没进去吗")
        // 判断验证码是否正确
        if (req.body.captcha != req.session.captcha) {
            console.log("报错了吗")
            req.session.captcha = "";
            throw new ValidationError("验证码错误!");
        }
    }
    const result = await LoginServices.login(req.body);
    // 在响应头中添加token
    if (result.token) {
        console.log(result.token);
        res.setHeader("Authorization", result.token);
    }
    res.send(FormatJson(0, "", result.data))
})

// 我是谁
router.get("/whoami", async (req, res, next) => {
    const token = req.get("Authorization");
    const result = await verifyJson(token);
    res.send(FormatJson(0, "", result));
})

// 更新管理员信息
router.put("/", async (req, res, next) => {
    const result = await LoginServices.updateLogin(req.body);
    res.send(result);
})

module.exports = router;